<?php

namespace app\api\model\xyvenue;
use addons\xyvenue\exception\Exception;
use app\api\model\xyvenue\order\Item as OrderItem;
use app\api\model\xyvenue\Package as PackageModel;
use app\api\model\xyvenue\user\User;
use app\api\model\xyvenue\Level;
use think\Model;
use app\api\model\xyvenue\Config;
use fast\Random;

class Venue extends Model
{

    // 表名
    protected $name = 'xyvenue_venue';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'duration_text',
        'status_text'
    ];


    /**
     * 场地详情
     */
    public static function getDetail($id)
    {
        $venue = self::where(['id'=>$id,'status'=>'normal'])->find();
        return $venue;
    }
    

    /**
     * 加载场地预约数据
     */
    public static function getInit($params)
    {

        extract($params);

        $venueList = self::where(['store_id'=>$store_id,'status'=>'normal'])->order('weigh desc')->select();

        if(empty($venueList)){
            new Exception('暂无可预约场地');
        }

        if($venue_id == 0){
            $venue_id = $venueList[0]['id'];
        }

        $curVenue = self::get($venue_id);

        //当前场地预定情况
        $ydList = [];
        $timeprice = $curVenue['timeprice'];
        $area = $curVenue['area'];

        //是否启用公休日和节假日特价
        if($curVenue['isholidayprice']){
            // 判断预定日期是否节假日
            $config = Config::getValueByName('xyvenue');
            $holidays = [];
            if(isset($config['holidays']) && !empty($config['holidays'])){
                $holidays = explode(',',$config['holidays']);
            } 
            $a = in_array($buy_date,$holidays);
            
            // 判断预定日期是否双休日
            $timestamp = strtotime($buy_date);
            $weekday = date('w', $timestamp);
            if($a || $weekday == 6 || $weekday == 0){
                $timeprice = $curVenue['holidayprice'];
            }

        }

        $user = User::info();

        foreach($timeprice as $key=>$tp){
            if($key + 1 == count($timeprice)){
                continue;
            }
            $tempTp = [];
            
            foreach($area as $key1=>$a){

                $isBuy = false;
                $jz = strtotime($buy_date.$tp['time']);
                $dq = time();
                if($dq <= $jz){
                    $isBuy = false;

                    //是否已经预定
                    $isYd = OrderItem::where([
                            'date'=>$buy_date,
                            'store_id'=>$store_id,
                            'venue_id'=>$venue_id,
                            'area'=>$a['name'],
                            'starttime'=>$tp['time'],
                            'endtime'=>$timeprice[$key+1]['time'],
                            'status'=>['in',[0,1,2]
                        ]
                    ])->find();

                    if(empty($isYd)){
                        //是否已包场
                        $isYd = PackageModel::where([
                                'startdate'=>['<=',$buy_date],
                                'enddate'=>['>=',$buy_date],
                                'store_id'=>$store_id,
                                'venue_id'=>$venue_id,
                                'arealist'=>['like','%'.$a['name'].'%'],
                                'timelist'=>['like','%'.$tp['time'].'-'.$timeprice[$key+1]['time'].'%'],
                            ])->find();
                    }

                    if(!empty($isYd)){
                        $isBuy = true;
                    }

                }else{
                    $isBuy = true;
                }

                //会员等级价格
                $price = $tp['price'];
                if(!empty($user) && $user->xyvenue_level_id > 0){
                    $userLevel = Level::where(['id'=>$user->xyvenue_level_id,'status'=>'normal'])->find();
                    if(!empty($userLevel)){
                        $price = bcdiv($price*$userLevel['discount'],10,2);
                    }
                }

                array_push($tempTp,['id'=>Random::alnum(20),'area'=>$a['name'],'price'=>$price,'isBuy'=>$isBuy,'isSelect'=>false,'startTime'=>$tp['time'],'endTime'=>$timeprice[$key+1]['time']]);
            }
            
            array_push($ydList,['time'=>$tp['time'],'area'=>$tempTp]);
        }
        $curVenue['ydList'] = $ydList;

        return ['venueList'=>$venueList,'curVenue'=>$curVenue];
    }

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    public function getAreaAttr($value)
    {
        return json_decode($value, true);
    }

    public function getTimepriceAttr($value)
    {
        return json_decode($value, true);
    }

    public function getHolidaypriceAttr($value)
    {
        return json_decode($value, true);
    }
    
    public function getDurationList()
    {
        return ['30' => __('Duration 30'), '45' => __('Duration 45'), '60' => __('Duration 60'), '90' => __('Duration 90')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Status normal'), 'hidden' => __('Status hidden')];
    }


    public function getDurationTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['duration']) ? $data['duration'] : '');
        $list = $this->getDurationList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    

}
